<template>
  <div class="main-container">
    <div class="content-card">
      <!-- 搜索-->
      <div style="margin-bottom: 20px;">
        <el-form inline="true" size="default">
          <el-form-item label="图书编号" >
            <el-input v-model="search1" placeholder="请输入图书编号"  clearable>
              <template #prefix><el-icon class="el-input__icon"><search/></el-icon></template>
            </el-input>
          </el-form-item >
          <el-form-item label="图书名称" >
            <el-input v-model="search2" placeholder="请输入图书名称"  clearable>
              <template #prefix><el-icon class="el-input__icon"><search /></el-icon></template>
            </el-input>
          </el-form-item >
          <el-form-item label="作者" >
            <el-input v-model="search3" placeholder="请输入作者"  clearable>
              <template #prefix><el-icon class="el-input__icon"><search /></el-icon></template>
            </el-input>
          </el-form-item >
          <el-form-item>
            <el-button type="primary" @click="load">
              <el-icon style="margin-right: 5px"><search/></el-icon>查询
            </el-button>
            <el-button @click="clear">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 按钮-->
      <div style="margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center;">
        <div>
          <el-button type="primary" @click = "add" v-if="user.role == 1">
            <el-icon style="margin-right: 5px"><plus /></el-icon>上架新书
          </el-button>
          <el-popconfirm title="确认删除?" @confirm="deleteBatch" v-if="user.role == 1">
            <template #reference>
              <el-button type="danger">批量删除</el-button>
            </template>
          </el-popconfirm>
        </div>
        <el-button type="warning" @click="viewCart" v-if="user.role == 2">
            <el-icon style="vertical-align: middle; margin-right: 5px"><shopping-cart /></el-icon>
            我的购物车 ({{cart.length}})
        </el-button>
      </div>

      <!-- 数据字段-->
      <el-table :data="tableData" stripe style="width: 100%" @selection-change="handleSelectionChange" :header-cell-style="{background:'#f5f7fa',color:'#606266'}">
        <el-table-column v-if="user.role ==1"
                        type="selection"
                        width="55">
        </el-table-column>
        <el-table-column prop="isbn" label="图书编号" sortable />
        <el-table-column prop="name" label="图书名称" />
        <el-table-column prop="price" label="价格" sortable>
          <template #default="scope">
            ¥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="author" label="作者" />
        <el-table-column prop="publisher" label="出版社" />
        <el-table-column prop="createTime" label="出版时间" sortable width="180"/>
        <el-table-column prop="inventory" label="库存" sortable width="100"/>
        <el-table-column prop="status" label="状态" v-if="user.role == 1" width="100">
          <template v-slot="scope">
            <el-tag v-if="scope.row.status == 1" type="success" effect="plain">上架中</el-tag>
            <el-tag v-else type="info" effect="plain">已下架</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="220">
          <template v-slot="scope">
            <div v-if="user.role == 1">
              <el-button size="small" type="primary" link @click ="handleEdit(scope.row)">修改</el-button>
              <el-popconfirm title="确认删除?" @confirm="handleDelete(scope.row.id)">
                <template #reference>
                  <el-button size="small" type="danger" link>删除</el-button>
                </template>
              </el-popconfirm>
              <el-button size="small" type="warning" link @click="toggleStatus(scope.row)" v-if="scope.row.status == 1">下架</el-button>
              <el-button size="small" type="success" link @click="toggleStatus(scope.row)" v-else>上架</el-button>
            </div>
            <div v-if="user.role == 2" style="display: flex; align-items: center;">
              <el-input-number v-model="scope.row.buyQuantity" :min="1" :max="scope.row.inventory" size="small" style="width: 100px; margin-right: 10px"></el-input-number>
              <el-button size="small" type="primary" @click="addToCart(scope.row)" :disabled="scope.row.status != 1 || scope.row.inventory <= 0">加入购物车</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

<!--测试,通知对话框-->
    <el-dialog
        v-model="dialogVisible3"
        v-if="numOfOutDataBook!=0"
        title="逾期详情"
        width="50%"
        :before-close="handleClose"
    >
        <el-table :data="outDateBook" style="width: 100%">
          <el-table-column prop="isbn" label="图书编号" />
          <el-table-column prop="bookName" label="书名" />
          <el-table-column prop="lendtime" label="借阅日期" />
          <el-table-column prop="deadtime" label="截至日期" />
        </el-table>

      <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="dialogVisible3 = false"
        >确认</el-button>
      </span>
      </template>
    </el-dialog>

    <!-- 购物车抽屉 -->
    <el-drawer v-model="cartVisible" title="我的购物车" direction="rtl" size="40%">
      <div style="padding: 20px; height: calc(100% - 100px); overflow-y: auto;">
          <el-table :data="cart" stripe border>
            <el-table-column prop="name" label="图书名称"></el-table-column>
            <el-table-column prop="price" label="单价" width="80"></el-table-column>
            <el-table-column label="数量" width="140">
                <template v-slot="scope">
                    <el-input-number v-model="scope.row.quantity" :min="1" :max="scope.row.inventory" size="mini" style="width: 100%" @change="updateCartItem(scope.row)"></el-input-number>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
                <template v-slot="scope">
                    <el-button type="danger" size="mini" circle @click="removeFromCart(scope.row)">
                        <el-icon><delete /></el-icon>
                    </el-button>
                </template>
            </el-table-column>
          </el-table>
      </div>
      <div style="position: absolute; bottom: 0; width: 100%; padding: 20px; background: #fff; border-top: 1px solid #eee;">
          <div style="margin-bottom: 10px; font-size: 18px; font-weight: bold; text-align: right;">
              总计: {{ cartTotal }} 元
          </div>
          <div style="display: flex; justify-content: space-between;">
            <el-button type="danger" @click="clearCartData(false)" :disabled="cart.length === 0">清空购物车</el-button>
            <el-button type="primary" style="width: 70%" @click="placeOrder" :disabled="cart.length === 0">立即购买</el-button>
          </div>
      </div>
    </el-drawer>

    <!--    分页-->
    <div style="margin-top: 20px; display: flex; justify-content: flex-end;">
      <el-pagination
          v-model:currentPage="currentPage"
          :page-sizes="[5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
      >
      </el-pagination>
    </div>
    </div> <!-- End of content-card -->

      <el-dialog v-model="dialogVisible" title="上架书籍" width="30%">
        <el-form :model="form" label-width="120px">

          <el-form-item label="图书编号">
            <el-input style="width: 80%" v-model="form.isbn"></el-input>
          </el-form-item>
          <el-form-item label="图书名称">
            <el-input style="width: 80%" v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="价格">
            <el-input style="width: 80%" v-model="form.price"></el-input>
          </el-form-item>
          <el-form-item label="作者">
            <el-input style="width: 80%" v-model="form.author"></el-input>
          </el-form-item>
          <el-form-item label="出版社">
            <el-input style="width: 80%" v-model="form.publisher"></el-input>
          </el-form-item>
          <el-form-item label="出版时间">
            <div>
              <el-date-picker value-format="YYYY-MM-DD" type="date" style="width: 80%" clearable v-model="form.createTime" ></el-date-picker>
            </div>
          </el-form-item>
          <el-form-item label="库存">
            <el-input-number v-model="form.inventory" :min="0" style="width: 80%"></el-input-number>
          </el-form-item>
        </el-form>
        <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
        </template>
      </el-dialog>

      <el-dialog v-model="dialogVisible2" title="修改书籍信息" width="30%">
        <el-form :model="form" label-width="120px">

          <el-form-item label="图书编号">
            <el-input style="width: 80%" v-model="form.isbn"></el-input>
          </el-form-item>
          <el-form-item label="图书名称">
            <el-input style="width: 80%" v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="价格">
            <el-input style="width: 80%" v-model="form.price"></el-input>
          </el-form-item>
          <el-form-item label="作者">
            <el-input style="width: 80%" v-model="form.author"></el-input>
          </el-form-item>
          <el-form-item label="出版社">
            <el-input style="width: 80%" v-model="form.publisher"></el-input>
          </el-form-item>
          <el-form-item label="出版时间">
            <div>
              <el-date-picker value-format="YYYY-MM-DD" type="date" style="width: 80%" clearable v-model="form.createTime" ></el-date-picker>
            </div>
          </el-form-item>
          <el-form-item label="库存">
            <el-input-number v-model="form.inventory" :min="0" style="width: 80%"></el-input-number>
          </el-form-item>
        </el-form>
        <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
        </template>
      </el-dialog>
  </div>
</template>

<script>
// @ is an alias to /src
import request from "../utils/request";
import {ElMessage} from "element-plus";
import moment from "moment";
export default {
  created(){
    let userStr = sessionStorage.getItem("user") ||"{}"
    this.user = JSON.parse(userStr)
    this.load()
    this.loadCart()
  },
  name: 'Book',
  computed: {
      cartTotal() {
          return this.cart.reduce((total, item) => total + item.price * item.quantity, 0).toFixed(2);
      }
  },
  methods: {
  // (this.isbnArray.indexOf(scope.row.isbn)) == -1
    handleSelectionChange(val){
      this.ids = val.map(v =>v.id)
    },
    deleteBatch(){
      if (!this.ids.length) {
        ElMessage.warning("请选择数据！")
        return
      }
      //  一个小优化，直接发送这个数组，而不是一个一个的提交删除
      request.post("/book/deleteBatch",this.ids).then(res =>{
        if(res.code === '0'){
          ElMessage.success("批量删除成功")
          this.load()
        }
        else {
          ElMessage.error(res.msg)
        }
      })
    },
    load(){
      this.numOfOutDataBook =0;
      this.outDateBook =[];
      request.get("/book",{
        params:{
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          search1: this.search1,
          search2: this.search2,
          search3: this.search3,
        }
      }).then(res =>{
        console.log(res)
        this.tableData = res.data.records
        // Initialize buyQuantity
        this.tableData.forEach(item => {
            item.buyQuantity = 1;
        });
        this.total = res.data.total
      })
    //
      /*
      if(this.user.role == 2){
        request.get("/bookwithuser",{
          params:{
            pageNum: "1",
            pageSize: this.total,
            search1: "",
            search2: "",
            search3: this.user.id,
          }
        }).then(res =>{
          console.log(res)
          this.bookData = res.data.records
          this.number = this.bookData.length;
          var nowDate = new Date();
          for(let i=0; i< this.number; i++){
            this.isbnArray[i] = this.bookData[i].isbn;
            let dDate = new Date(this.bookData[i].deadtime);
            if(dDate < nowDate){
              this.outDateBook[this.numOfOutDataBook] = {
                isbn:this.bookData[i].isbn,
                bookName : this.bookData[i].bookName,
                deadtime : this.bookData[i].deadtime,
                lendtime : this.bookData[i].lendtime,
              };
              this.numOfOutDataBook = this.numOfOutDataBook + 1;
            }
          }
          console.log("in load():" +this.numOfOutDataBook );
        })
      }
      */
      //
    },
    clear(){
      this.search1 = ""
      this.search2 = ""
      this.search3 = ""
      this.load()
    },

    handleDelete(id){
      request.delete("book/" + id ).then(res =>{
        console.log(res)
        if(res.code == 0 ){
          ElMessage.success("删除成功")
        }
        else
          ElMessage.error(res.msg)
        this.load()
      })
    },
    handlereturn(id,isbn,bn){
      // (this.isbnArray.indexOf(scope.row.isbn)) == -1
      // for(let i=0; i<this.numOfOutDataBook; i++){
      //   if(this.outDateBook[i].isbn == isbn){
      //     this.numOfOutDataBook = this.numOfOutDataBook -1;
      //     console.log("in handlereturn: " + this.numOfOutDataBook);
      //     break;
      //   }
      // }
      this.form.status = "1"
      this.form.id = id
      request.put("/book",this.form).then(res =>{
        console.log(res)
        if(res.code == 0){
          ElMessage({
            message: '还书成功',
            type: 'success',
          })
        }
        else {
          ElMessage.error(res.msg)
        }
      //
        this.form3.isbn = isbn
        this.form3.readerId = this.user.id
        let endDate = moment(new Date()).format("yyyy-MM-DD HH:mm:ss")
        this.form3.returnTime = endDate
        this.form3.status = "1"
        console.log(bn)
        this.form3.borrownum = bn
        request.put("/LendRecord1/",this.form3).then(res =>{
          console.log(res)
          let form3 ={};
          form3.isbn = isbn;
          form3.bookName = name;
          form3.nickName = this.user.username;
          form3.id = this.user.id;
          form3.lendtime = endDate;
          form3.deadtime = endDate;
          form3.prolong  = 1;
          request.post("/bookwithuser/deleteRecord",form3).then(res =>{
            console.log(res)
            this.load()
          })

        })
      //
      })
      // this.form3.isbn = isbn
      // this.form3.readerId = this.user.id
      // let endDate = moment(new Date()).format("yyyy-MM-DD HH:mm:ss")
      // this.form3.returnTime = endDate
      // this.form3.status = "1"
      // console.log(bn)
      // this.form3.borrownum = bn
      // request.put("/LendRecord1/",this.form3).then(res =>{
      //   console.log(res)
      // })
      // let form3 ={};
      // form3.isbn = isbn;
      // form3.bookName = name;
      // form3.nickName = this.user.username;
      // form3.id = this.user.id;
      // form3.lendtime = endDate;
      // form3.deadtime = endDate;
      // form3.prolong  = 1;
      // request.post("/bookwithuser/deleteRecord",form3).then(res =>{
      //   console.log(res)
      //   this.load()
      // })
    },
    handlelend(id,isbn,name,bn){
      if(this.number ==5){
        ElMessage.warning("您不能再借阅更多的书籍了")
        return;
      }
      if(this.numOfOutDataBook !=0){
        ElMessage.warning("在您归还逾期书籍前不能再借阅书籍")
        return;
      }
      this.form.status = "0"
      this.form.id = id
      this.form.borrownum = bn+1
      console.log(bn)
      request.put("/book",this.form).then(res =>{
        console.log(res)
        if(res.code == 0){
          ElMessage({
            message: '借阅成功',
            type: 'success',
          })
        }
        else {
          ElMessage.error(res.msg)
        }
      })

      this.form2.status = "0"
      this.form2.isbn = isbn
      this.form2.bookname = name
      this.form2.readerId = this.user.id
      this.form2.borrownum = bn+1
      console.log(this.form2.borrownum)
      console.log(this.user)
      let startDate = moment(new Date()).format("yyyy-MM-DD HH:mm:ss");
      this.form2.lendTime = startDate
      console.log(this.user)
      request.post("/LendRecord",this.form2).then(res =>{
        console.log(res)
        this.load();

      })
      let form3 ={};
      form3.isbn = isbn;
      form3.bookName = name;
      form3.nickName = this.user.username;
      form3.id = this.user.id;
      form3.lendtime = startDate;
      let nowDate = new Date(startDate);
      nowDate.setDate(nowDate.getDate()+30);
      form3.deadtime = moment(nowDate).format("yyyy-MM-DD HH:mm:ss");
      form3.prolong  = 1;
      request.post("/bookwithuser/insertNew",form3).then(res =>{
        console.log(res)
        this.load()
      })
    },
    add(){
      this.dialogVisible= true
      this.form ={}
    },
    save(){
      //ES6语法
      //地址,但是？IP与端口？+请求参数
      // this.form?这是自动保存在form中的，虽然显示时没有使用，但是这个对象中是有它的
      if(this.form.id){
        request.put("/book",this.form).then(res =>{
          console.log(res)
          if(res.code == 0){
            ElMessage({
              message: '修改书籍信息成功',
              type: 'success',
            })
          }
          else {
            ElMessage.error(res.msg)
          }

          this.load()
          this.dialogVisible2 = false
        })
      }
      else {
        this.form.borrownum = 0
        this.form.status = 1
        request.post("/book",this.form).then(res =>{
          console.log(res)
          if(res.code == 0){
            ElMessage.success('上架书籍成功')
          }
          else {
            ElMessage.error(res.msg)
          }
          this.load()
          this.dialogVisible = false
        })
      }

    },
    // formatter(row) {:formatter="formatter"
    //   return row.address
    // },

    handleEdit(row){
      this.form = JSON.parse(JSON.stringify(row))
      this.dialogVisible2 = true
    },
    handleSizeChange(pageSize){
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum){
      this.pageNum = pageNum
      this.load()
    },
    toLook(){
      this.dialogVisible3 =true;
    },
    // New Methods for Order System
    loadCart() {
        if (this.user.role != 2) return; // Only for normal users
        request.get("/cart").then(res => {
            if (res.code == '0') {
                // Map backend cart structure to frontend structure
                // Backend: [{id, bookId, count, book: {name, price, inventory, isbn, ...}}]
                this.cart = res.data.map(item => ({
                    id: item.id, // Cart ID
                    bookId: item.bookId,
                    isbn: item.book.isbn,
                    name: item.book.name,
                    price: item.book.price,
                    quantity: item.count,
                    inventory: item.book.inventory
                }));
            }
        });
    },
    toggleStatus(row) {
        let newStatus = row.status == 1 ? 0 : 1;
        let action = newStatus == 1 ? "上架" : "下架";
        let updatedRow = JSON.parse(JSON.stringify(row));
        updatedRow.status = newStatus;
        
        request.put("/book", updatedRow).then(res => {
            if (res.code == 0) {
                ElMessage.success(action + "成功");
                this.load();
            } else {
                ElMessage.error(res.msg);
            }
        });
    },
    addToCart(row) {
        let quantityToAdd = row.buyQuantity || 1;
        
        request.post("/cart", {
            bookId: row.id,
            count: quantityToAdd
        }).then(res => {
            if (res.code == '0') {
                ElMessage.success("已添加到购物车");
                this.loadCart();
            } else {
                ElMessage.error(res.msg || "添加失败");
            }
        });
    },
    viewCart() {
        this.loadCart();
        this.cartVisible = true;
    },
    removeFromCart(row) {
        request.delete("/cart/" + row.id).then(res => {
            if (res.code == '0') {
                ElMessage.success("移除成功");
                this.loadCart();
            } else {
                ElMessage.error(res.msg || "移除失败");
            }
        });
    },
    updateCartItem(row) {
        request.put("/cart", {
            id: row.id,
            count: row.quantity
        }).then(res => {
            if (res.code != '0') {
                ElMessage.error(res.msg || "更新失败");
                this.loadCart(); // Revert on failure
            }
        });
    },
    clearCartData(silent = false) {
        if (this.cart.length === 0) return;
        const deletePromises = this.cart.map(item => request.delete("/cart/" + item.id));
        Promise.all(deletePromises).then(() => {
             if (!silent) ElMessage.success("购物车已清空");
             this.loadCart();
        });
    },
    placeOrder() {
        if (this.cart.length === 0) return;
        
        let orderData = {
            userId: this.user.id,
            details: this.cart.map(item => ({
                isbn: item.isbn,
                quantity: item.quantity
            }))
        };

        request.post("/order", orderData).then(res => {
            if (res.code == '0') {
                ElMessage.success("下单成功");
                // Clear cart after successful order
                const deletePromises = this.cart.map(item => request.delete("/cart/" + item.id));
                Promise.all(deletePromises).then(() => {
                     this.cart = [];
                     this.cartVisible = false;
                     this.load(); // Refresh inventory
                     this.loadCart();
                });
            } else {
                ElMessage.error(res.msg || "下单失败");
            }
        });
    },
  },
  data() {
    return {
      form: {},
      form2:{},
      form3:{},
      dialogVisible: false,
      dialogVisible2: false,
      search1:'',
      search2:'',
      search3:'',
      total:10,
      currentPage:1,
      pageSize: 10,
      tableData: [],
      user:{},
      number:0,
      bookData:[],
      isbnArray:[],
      outDateBook:[],
      numOfOutDataBook: 0,
      dialogVisible3 : true,
      cartVisible: false,
      cart: [],
    }
  },
}
</script>
